<?php

/**
 * Books
 *  
 * @author bichnkn
 * @version 
 */

require_once 'Zend/Db/Table/Abstract.php';

class Application_Model_DbTable_Books extends Zend_Db_Table_Abstract {
	/**
	 * The default table name
	 */
	protected $_name = 'books';
	protected $_primary= 'id';
	
	public function listBooks(){
		$result = $this->fetchAll();
		$entries = array();
		foreach($result as $row){
			$entry = new Application_Model_Book();
			$entry->setId($row->id)
			->setTitle($row->title)
			->setAuthor($row->author)
			->setPrice($row->price)
			->setDescription($row->description)
			->setPosted_by($row->posted_by)
			->setPosted_date($row->posted_date)
			->setImage($row->image);
			
			$entries[] = $entry;
		}
		
		return $entries;
	}
	
	public function addBook(Application_Model_Book $book){
		$data = array('title'=>$book->title,
				'author'=>$book->author,
				'price'=>$book->price,
				'posted_date'=>date('Y-m-d H:m:s'),
				'posted_by'=>'admin',
				'description'=>$book->description,
				'image'=>$book->image);
		$this->insert($data);
	}
	
	public function getBook($id, $type = null){
		$id = (int) $id;
		$row = $this->fetchRow('id = '.$id);
		if(!$row){
			throw new Exception("Can't find book id ".$id);
		}else{
			if($type == 'array'){
				$entry = $row->toArray();
			}else{
				$entry = new Application_Model_Book();
				$entry->setId($row->id)
				->setTitle($row->title)
				->setAuthor($row->author)
				->setPrice($row->price)
				->setDescription($row->description)
				->setPosted_by($row->posted_by)
				->setPosted_date($row->posted_date)
				->setImage($row->image);
			}
			return $entry;
		}
	}
	
	public function saveBook(Application_Model_Book $book, $id){
		$data = array('title'=>$book->title,
				'author'=>$book->author,
				'price'=>$book->price,
				'description'=>$book->description,
				'image'=>$book->image);
		$id = $book->id;
		$this->update($data, ' id = '.$id);
	}
	
	public function saveBookNoImg(Application_Model_Book $book, $id){
		$data = array('title'=>$book->title,
				'author'=>$book->author,
				'price'=>$book->price,
				'description'=>$book->description);
		$id = $book->id;
		$this->update($data, ' id = '.$id);
	}
	
	public function deleteBook($id){
		$this->delete(' id = '.$id);
	}
}
